Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

438
Vistas
How to remove parentheses and replace "white space" with "-" in php using preg_replace

This is What I Have - Huawei MatePad 11 (2021)

This is what I want - Huawei-MatePad-11-2021

This is what I have done so far. (only it replaces "white space" with "-".

echo preg_replace('/[[:space:]]+/', '-', $test);

I want to remove parentheses, and want to replace "white space" with "-" at once. How to do it?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

$text = 'Huawei MatePad 11 (2021)';
$text = preg_replace('/[(|)]/', '', preg_replace('/\s+/', '-', $text));

echo($text);
over 4 years ago · Santiago Trujillo Denunciar

0

$test = preg_replace('/[[:space:]]+/', '-', $test); # Replace space
$test = preg_replace('/[\(|\)]+/', '', $test);      # Replace parenthesis 

echo $test;
over 4 years ago · Santiago Trujillo Denunciar

0

You might also use a single pattern with preg_replace_callback and match from an opening till closing parenthesis.

\(([^()]+)\)|\h+

The pattern matches:

  • \( Match (
  • ([^()]+) Capture group 1 match 1+ chars other than ( )
  • \) Match )
  • | Or
  • \h+ Match 1 or more horizontal whitespace chars

Php demo | Regex demo

For example return group 1 using $m[1] if it exists, else return -

$s = "Huawei MatePad 11 (2021)";
$regex = "/\(([^()]+)\)|\h+/";
$result = preg_replace_callback($regex, function($m) {
    return array_key_exists(1, $m) ? $m[1] : '-';
}, $s);
echo $result;

Output

Huawei-MatePad-11-2021
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda